<template>
	<view>
		<u-tabs
			:list="splist" 
			:height="80" 
			name="categoryName"  
			:active-color="'#EF7B3A'"	
			:is-scroll="false" 
			:current="current" 
			@change="handleTabChange" 
			style="width: 100%;"
			:transition="tabTransition"
		></u-tabs>
		<view class="coupon_list">
			<view class="coupon_item" v-for="(item,index) in coupon_list" :key="index">
				<view class="ordernumber">
					 <view>订单编号：{{item.orderNo}}</view>
					 <view>{{current == 0  ? (item.refundApplyStatus == 1 ? '退款中' : (item.refundApplyStatus == 3 ? '审核失败' : '待核销')) : (current == 1 ? '已核销' : (current == 2 ? '已失效' : '已退款'))}}</view>
				</view>
                 <view class="content">
					 <view class="coupon_img">
					 	<image :src="'https:' + item.iconUrl" mode=""></image>
					 </view>
					 <view class="ifom">
						 <view class="name">{{item.title}}</view>
						 <view class="dibs">
						 	<view class="price">
						 		<text>￥</text>
						 		{{item.paidAmount}}
						 	</view>
						 	<view class="yh">
						 		{{item.tags[0] == '满减券' ? `满 ${item.useThreshold} 元可用` : (item.tags[0] == '代金券' ? `${item.paidAmount}抵${item.couponValue}代金券` : '')}}</view>
						 	</view>
							<view class="period">
								有效期到：{{item.effectEnd}}
							</view>
						 </view>
					 </view>
					 <view class="btoom">
						 <view class="time">
							 <text v-if="current == 0">
								 领取日期：{{ item.createTime | formatDate}}
							 </text>
							 <text v-if="current == 1">
								 使用日期：{{ item.useTime | formatDate}}
							 </text>
						 </view>
						 <view
						   class="verify-btn1" 
						   @click="goRefund(item)" 
						   v-if="item.writeOffStatus === 0 && current != 3 && item.refundApplyStatus != 1"
						 >
						   <view>退款</view>
						 </view>
						 <view class="btn" @click="Card(item.id)"  v-if="current == 0 && item.refundApplyStatus != 1">
							 <image src="/static/my/ewm.png" mode="widthFix"></image>
							 <view>去核销</view>
						 </view>
					 </view>
					 <view class="bohx" v-if="item.refundApplyStatus == 3">
					  <view>退款失败原因：</view>
					  <view style="flex: 1;">{{item.auditRemark}}</view>
					 </view>
				 </view>
			</view>
			<!-- 加载更多提示 -->
			<view class="load-more">
				<view class="load-more-content">
					<view v-if="hasMoreData" class="load-more-animation">
						<view class="loading-dot"></view>
						<view class="loading-dot"></view>
						<view class="loading-dot"></view>
					</view>
					<text>{{ hasMoreData ? '加载中...' : '没有更多数据了' }}</text>
				</view>
			</view>
			<!-- 调试按钮 -->
		</view>
	</view>
</template>

<script>
import { userCouponpage } from '@/core/api/index.js'
import { mapState } from 'vuex';

export default {
	computed: {
		...mapState({
			userInfo: state => state.user.userInfo
		})
	},
	data() {
		return {
			current: 0,
			splist: [
				{
					categoryName: '可用优惠券'
				},
				{
					categoryName: '已使用'
				},
				{
					categoryName: '已失效'
				},
				{
					categoryName: '已退款'
				}
			],
			coupon_list: [],
			writeOffStatus: 0,
			isExpired: 0,
			requst: false,
			// 分页相关变量
			currentPage: 1,
			pageSize: 5, // 调小以便测试
			total: 0,
			hasMoreData: true,
			isLoading: false,
			showLoadMore: false,
			isLoadingMore: false,
			__DEV__: process.env.NODE_ENV !== 'production' // 开发环境标识
		}
	},
	onShow() {
		this.fetchCoupons()
	},
	// 监听页面滚动到底部
	onReachBottom() {
		console.log('【触底事件】showLoadMore:', this.showLoadMore, 
			'hasMoreData:', this.hasMoreData, 
			'isLoading:', this.isLoading)
		if (this.isLoading || !this.hasMoreData) return
		this.loadMoreCoupons()
	},
	methods: {
		goRefund(item){
			uni.navigateTo({
			  url: `/pages/my/refund?item=${encodeURIComponent(JSON.stringify(item))}&type=0`
			});
		},
		handleTabChange(index) {
			this.current = index
			if (index == 1) {
				this.writeOffStatus = 1
				this.isExpired = 0
			} else if (index == 2) {
				this.writeOffStatus = 0
				this.isExpired = 1
			} else {
				this.writeOffStatus = 0
				this.isExpired = 0
			}
			// 切换标签时重置分页
			this.resetPagination()
			this.fetchCoupons()
		},
		Card(id) {
			uni.navigateTo({
				url: '/pages/coupon/cardverification?id=' + id
			})
		},
		// 重置分页状态
		resetPagination() {
			this.currentPage = 1
			this.hasMoreData = true
			this.coupon_list = []
			this.showLoadMore = false
			this.isLoading = false
			this.isLoadingMore = false
		},
		// 加载更多优惠券
		loadMoreCoupons() {
			console.log('【加载更多】currentPage:', this.currentPage, 
				'isLoadingMore:', this.isLoadingMore)
			if (this.isLoadingMore) return
			
			this.isLoadingMore = true
			this.showLoadMore = true // 立即显示加载状态
			this.currentPage++
			this.fetchCoupons(true)
		},
		// 获取优惠券列表
		async fetchCoupons(isLoadMore = false) {
			console.log('【数据请求】page:', this.currentPage, 'isLoadMore:', isLoadMore)
			try {
				let params = {
					page: this.currentPage,
					size: this.pageSize,
					condition: {
						userId: this.userInfo.id,
						writeOffStatus: this.writeOffStatus,
						isExpired: this.isExpired,
					   ...(this.current === 3  && { refundStatus: 1 }),
					   ...(this.current === 0  && { refundStatus: 0 })
					}
				}
				const { data } = await userCouponpage(params)
				
				console.log('【接口响应】data:', data)
				const newRecords = data.records || []
				this.total = data.total || 0
				
				// 判断是否还有更多数据
				this.hasMoreData = 
					this.currentPage * this.pageSize < this.total && 
					newRecords.length >= this.pageSize
				
				console.log('【数据判断】currentPage:', this.currentPage, 
					'pageSize:', this.pageSize, 
					'total:', this.total, 
					'newRecords.length:', newRecords.length,
					'hasMoreData:', this.hasMoreData)
				
				if (isLoadMore) {
					this.coupon_list = [...this.coupon_list, ...newRecords]
					console.log('【数据合并】当前列表长度:', this.coupon_list.length)
				} else {
					this.coupon_list = newRecords
					console.log('【数据重置】当前列表长度:', this.coupon_list.length)
				}
				
				this.requst = true
			} catch (error) {
				console.error('【请求错误】', error)
				if (this.currentPage > 1) this.currentPage--
			} finally {
				this.isLoading = false
				this.isLoadingMore = false
				
				// 直接更新showLoadMore，无需延迟
				this.showLoadMore = this.hasMoreData
				console.log('【加载完成】showLoadMore:', this.showLoadMore)
			}
		}
	}
}
</script>

<style lang="scss">
	.msg {
		margin: 100rpx auto;
		text-align: center;
	}
	
	.coupon_list {
		padding: 20rpx 30rpx;
		.coupon_item {
			background-color: #fff;
			border-radius: 10rpx;
			margin-top: 15rpx;
			// padding-bottom: 25rpx;
			.ordernumber {
				display: flex;
				justify-content: space-between;
				padding: 22rpx 25rpx 22rpx 15rpx;
				view:nth-child(1) {
					font-size: 24rpx;
					color: #333;
				}
				color: var(--Color, #F26B2E);
				font-size: 28rpx;
				border-bottom: 1rpx solid #F3F3F3;
			}
			.content {
				padding: 20rpx 20rpx;
				display: flex;
			}
			.coupon_img {
				width: 120rpx;
				height: 120rpx;
				image {
					width: 100%;
					border-radius: 10rpx;
					height: 100%;
				}
			}
			.ifom {
				margin-left: 20rpx;
				.name {
					font-size: 28rpx;
					font-weight: 700;
					width: fit-content;
					position: relative;
				}
				.pup_tpye {
					font-size: 20rpx;
					background-color: #FADFCF;
					color: #f98c50;
					position: absolute;
					padding: 5rpx 15rpx;
					top: 5%;
					right: -77%;
				}
				
				.dibs {
					display: flex;
					align-items: center;
					margin: 5rpx 0;
					.price {
						font-size: 32rpx;
						color: #EC691C;
						font-weight: 700;
						text {
							font-size: 30rpx;
						}
					}
					.yh {
						margin-left: 20rpx;
						font-size: 24rpx;
						color: #757575;
					}
				}
				.period {
					font-size: 24rpx;
				}
			}
			
		}
		.bohx{
			font-size: 24rpx;
			color: #F26B2E;
			display: flex;
			padding: 0 20rpx;
			padding-bottom: 25rpx;
			view{
				// width: 200rpx;
				// color: #333;
			}
		}
		.btoom {
			display: flex;
			padding: 0rpx 25rpx 22rpx 20rpx;
			justify-content: space-between;
			align-items: center;
			image {
				width: 24rpx;
				height: 24rpx;
				margin-right: 5rpx;
			}
			.time {
				font-size: 24rpx;
				color: var(--, #A3A3A3);
			}
			.btn {
				width: 130rpx;
				height: 52rpx;
				background: var(--Color, #F26B2E);
				color: #fff;
				display: flex;
				align-items: center;
				font-size: 24rpx;
				border-radius: 30rpx;
				justify-content: center;
			}
		}
	}
	
	/* 加载更多样式 */
	.load-more {
		text-align: center;
		padding: 30rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.load-more-content {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.load-more-animation {
		display: flex;
		margin-bottom: 10rpx;
	}
	
	.loading-dot {
		width: 16rpx;
		height: 16rpx;
		margin: 0 8rpx;
		background-color: #F26B2E;
		border-radius: 50%;
		animation: loading 1.4s infinite ease-in-out both;
	}
	
	.loading-dot:nth-child(1) {
		animation-delay: -0.32s;
	}
	
	.loading-dot:nth-child(2) {
		animation-delay: -0.16s;
	}
	
	@keyframes loading {
		0%,
		80%,
		100% {
			transform: scale(0);
		}
		40% {
			transform: scale(1);
		}
	}
	
	/* 调试按钮 */
	.debug-btn {
		position: fixed;
		bottom: 30rpx;
		right: 30rpx;
		padding: 20rpx 40rpx;
		background-color: #EF7B3A;
		color: #fff;
		border-radius: 30rpx;
		z-index: 100;
		font-size: 24rpx;
	}
	.verify-btn , .verify-btn1{
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  width: 130rpx;
	  height: 52rpx;
	  background-color: #F26B2E;
	  color: #fff;
	  font-size: 24rpx;
	  border-radius: 26rpx;
	}
	.verify-btn1{
		background-color: #fff;
		color: #A3A3A3;
		border: 1rpx solid #A3A3A3;
		margin-left: 25rpx;
	}
	
</style>